package com.atguigu.serviceedu.service.impl;

import com.atguigu.servicebase.handler.GuliException;
import com.atguigu.serviceedu.entity.EduChapter;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.serviceedu.mapper.EduChapterMapper;
import com.atguigu.serviceedu.service.EduChapterService;
import com.atguigu.serviceedu.service.EduVideoService;
import com.atguigu.serviceedu.vo.ChapterVo;
import com.atguigu.serviceedu.vo.VideoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2021-12-19
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideo(String courseId) {
        List<EduChapter> eduChapters = baseMapper.selectList(new QueryWrapper<EduChapter>().eq("course_id", courseId));
        List<ChapterVo> chapterVos = eduChapters.stream().map(item -> {
            ChapterVo chapterVo = new ChapterVo();
            chapterVo.setId(item.getId());
            chapterVo.setTitle(item.getTitle());
            List<EduVideo> eduVideos = videoService.list(new QueryWrapper<EduVideo>().eq("chapter_id", item.getId()));
            List<VideoVo> videoVos = eduVideos.stream().map(vio -> {
                VideoVo videoVo = new VideoVo();
                videoVo.setId(vio.getId());
                videoVo.setTitle(vio.getTitle());
                videoVo.setFree(vio.getIsFree());
                videoVo.setVideoSourceId(vio.getVideoSourceId());
                return videoVo;
            }).collect(Collectors.toList());
            chapterVo.setChildren(videoVos);
            return chapterVo;
        }).collect(Collectors.toList());
        return chapterVos;
    }

    @Override
    public boolean removeChapterById(String id) {
        //根据id查询是否存在视频，如果有则提示用户尚有子节点
        if(videoService.getCountByChapterId(id)){
            throw new GuliException(20001,"该分章节下存在视频课程，请先删除视频课程");
        }

        Integer result = baseMapper.deleteById(id);
        return null != result && result > 0;
    }

    @Override
    public void removeByCourseId(String id) {
        this.remove(new QueryWrapper<EduChapter>().eq("course_id",id));
    }
}
